#!/usr/bin/env python
# coding=utf-8

from Crypto.Cipher import AES

asekey = "4BB97A76D2496F80"
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

class MyCrypt(object):
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_ECB
        self.padding = '\0'
 
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode)
        length = 16
        count = text.count('')
        if count < length:
            add = (length - count) + 1
            text += (self.padding * add)
        elif count > length:
            add = (length - (count % length)) + 1
            text += (self.padding * add)
        self.ciphertext = cryptor.encrypt(text)
        return self.ciphertext.encode('hex')
 
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode)
        plain_text = cryptor.decrypt(text).decode('hex')
        return plain_text.rstrip("\0")

if __name__ == '__main__':
    text = '我们是单身男上聚集地'
    cipher = AES.new(asekey,AES.MODE_ECB)
    encrypted = cipher.encrypt(pad(text)).encode('hex')
    print encrypted    
    decrypted = unpad(cipher.decrypt(encrypted.decode('hex')))
    print decrypted
    
    myc = MyCrypt(asekey)
    a = myc.encrypt(text)
    print a
    b = myc.decrypt(a)
    print b
    
    d = myc.decrypt('htVN5AbqxYw30/va+ySQcQ1IeZPjbxEQJiKKH/gh2c0=')
    print d
